package com.zuora.interview.topn.processor.step1;

import com.google.common.base.Splitter;
import com.zuora.interview.topn.bean.Constants;
import com.zuora.interview.topn.util.Clock;
import com.zuora.interview.topn.util.LogHelper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by chunyang.gao on 2016/8/23.
 */
public class UserPartitioner {

    private static final Logger logger = LoggerFactory.getLogger(UserPartitioner.class);

    private static final Logger console = LoggerFactory.getLogger("console");

    Splitter commaSplitter = Splitter.on(",");

    public void work() throws IOException {
        Clock clock = Clock.start();
        new UserPartitioner().test();
        console.warn("step1 in {} ms", clock.checkTime());
    }

    private void test() throws IOException {
        LineIterator it = FileUtils.lineIterator(new File(Constants.logPath+"base.log"));
        try {
            while (it.hasNext()) {
                String line = it.nextLine();
                List<String> parts = commaSplitter.splitToList(line);
                String username = parts.get(0);
                int partionId = generateUserHash(username);
                LogHelper.set(partionId+"");
                logger.info(line);
                LogHelper.clear();
            }
        } finally {
            LineIterator.closeQuietly(it);
        }
    }

    private int generateUserHash(String username){
        char first = 0;
        if(username.length()>1){
            first = username.charAt(username.length()-2);
        }
        char second = username.charAt(username.length()-1);
        String joinedChar = (first+0)+""+(second+0);
        return Integer.valueOf(joinedChar)%1024;
    }
}
